﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RXY_Mall.Application.Shop.Dto;
using RXY_Mall.Core;
using RXY_Mall.Domain;
using System.Data.Entity;
using RXY_Mall.Core.Tool;
using RXY_Mall.Core.Sms;

namespace RXY_Mall.Application.Shop
{
    public class ShopService : RXY_MallAppServiceBase, IShopService
    {
        #region 商家
        public async Task<Response<bool>> AddorEditCompany(int managerId, CompanyInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.company_name))
            {
                errorList.Append("商家名称不能为空；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<bool>(errorList.ToString());
            }
            if (input.id > 0)
            {
                var entity = db.gw_suppliers.FirstOrDefault(i => i.id == input.id);
                if (entity != null)
                {
                    //entity.company_name = input.company_name;
                    entity.organizing_bar = input.organizing_bar == null ? "" : input.organizing_bar;
                    entity.expiry_date = input.expiry_date == null ? "" : input.expiry_date;
                    entity.corporation = input.corporation == null ? "" : input.corporation;
                    entity.corporation_phone = input.corporation_phone == null ? "" : input.corporation_phone;
                    entity.business_scope = input.business_scope == null ? "" : input.business_scope;
                    entity.business_llicence = input.business_llicence == null ? "" : input.business_llicence;
                    entity.face_card = input.face_card == null ? "" : input.face_card;
                    entity.opposite_card = input.opposite_card == null ? "" : input.opposite_card;
                    entity.card_date = input.card_date == null ? "" : input.card_date;
                    entity.province = input.province;
                    entity.city = input.city;
                    entity.country = input.country;
                    entity.area = input.area;
                    entity.address = input.address == null ? "" : input.address;
                    entity.real_name = input.real_name == null ? "" : input.real_name;
                    entity.wordtel = input.contacts_phone == null ? "" : input.contacts_phone;
                    var result = await db.SaveChangesAsync();
                    LogHelper.WriteLog("管理员" + managerId + "修改：商家" + entity.id);
                    return ReturnSuccess<bool>(true);
                }
                return ReturnError<bool>("公司信息不存在");
            }
            else
            {
                var entity = new gw_suppliers()
                {
                    company_name = input.company_name,
                    organizing_bar = input.organizing_bar == null ? "" : input.organizing_bar,
                    expiry_date = input.expiry_date == null ? "" : input.expiry_date,
                    corporation = input.corporation == null ? "" : input.corporation,
                    corporation_phone = input.corporation_phone == null ? "" : input.corporation_phone,
                    business_scope = input.business_scope == null ? "" : input.business_scope,
                    business_llicence = input.business_llicence == null ? "" : input.business_llicence,
                    face_card = input.face_card == null ? "" : input.face_card,
                    opposite_card = input.opposite_card == null ? "" : input.opposite_card,
                    card_date = input.card_date == null ? "" : input.card_date,
                    province = input.province,
                    city = input.city,
                    country = input.country,
                    area = input.area,
                    address = input.address == null ? "" : input.address,
                    real_name = input.real_name == null ? "" : input.real_name,
                    wordtel = input.contacts_phone == null ? "" : input.contacts_phone,
                    add_time = DateTime.Now,
                    status = 1,
                    deleted = false
                };
                var model = db.gw_suppliers.Add(entity);
                var result = await db.SaveChangesAsync();
                if (result > 0)
                {
                    LogHelper.WriteLog("管理员" + managerId + "添加：商家" + model.id);
                    return ReturnSuccess<bool>(true);
                }
                else
                {
                    return ReturnError<bool>("保存失败，请重试！");
                }
            }

        }

        public IList<CompanyList> GetCompanysByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, string companyName, string realName, int status, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            var list = db.gw_companys
                .Include(c => c.gw_company_info)
                .Where(i => i.deleted == false)
                .Select(item => new CompanyList
                {
                    id = item.id,
                    company_name = item.name,
                    contacts_name = item.contacts_name,
                    contacts_phone = item.contacts_phone,
                    start_date = item.start_time,
                    end_time = item.end_time,
                    status = item.status,
                    add_time = item.add_time,

                    corporation = "",
                    corporation_phone = "",
                    //expiry_date = item.expiry_date,
                    //real_name = item.real_name,
                    //card_date = item.card_date,

                });
            if (status > -1)
            {
                list = list.Where(m => m.status == status);
            }
            if (!string.IsNullOrWhiteSpace(companyName))
            {
                list = list.Where(m => m.company_name.Contains(companyName));
            }
            if (!string.IsNullOrWhiteSpace(realName))
            {
                list = list.Where(m => m.contacts_name.Contains(realName));
            }
            if (!string.IsNullOrWhiteSpace(dateMin))
            {
                dtMin = DateTime.Parse(dateMin);
            }
            if (!string.IsNullOrWhiteSpace(dateMax))
            {
                dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
            }
            list = list.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }

        public Response<IPagedList<CompanyList>> GetCompanysByPage(string dateMin, string dateMax, string companyName, string realName, int status, int page_index = 1, int page_size = 20, int shop_id = -1)
        {
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            Response<IPagedList<CompanyList>> result = new Response<IPagedList<CompanyList>>();
            try
            {
                var source = db.gw_companys
                            .Include(c => c.gw_company_info)
                           .Where(i => i.deleted == false)
                           .Select(item => new CompanyList
                           {
                               id = item.id,
                               company_name = item.name,
                               contacts_name = item.contacts_name,
                               contacts_phone = item.contacts_phone,
                               start_date = item.start_time,
                               end_time = item.end_time,
                               status = item.status,
                               add_time = item.add_time,

                               corporation = "",
                               corporation_phone = "",
                                //expiry_date = item.expiry_date,
                                //real_name = item.real_name,
                                //card_date = item.card_date,

                            });
                if (status > -1)
                {
                    source = source.Where(m => m.status == status);
                }
                if (!string.IsNullOrWhiteSpace(companyName))
                {
                    source = source.Where(m => m.company_name.Contains(companyName));
                }
                if (!string.IsNullOrWhiteSpace(realName))
                {
                    source = source.Where(m => m.contacts_name.Contains(realName));
                }
                if (!string.IsNullOrWhiteSpace(dateMin))
                {
                    dtMin = DateTime.Parse(dateMin);
                }
                if (!string.IsNullOrWhiteSpace(dateMax))
                {
                    dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
                }
                source = source.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);

                source = source.OrderByDescending(m => m.add_time);

                var pagelist = new PagedList<CompanyList>(source, page_index, page_size);

                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public CompanyInput GetCompanyById(int id)
        {
            var entity = db.gw_companys.Select(c => new CompanyInput()
            {
                id = c.id,
                company_name = c.name,
                province_code = c.province_code,
                city_code = c.city_code,
                country_code = c.country_code,
                area = c.area,
                address = c.address,
                contacts_phone = c.contacts_phone,
                end_time = c.end_time,
                //real_name = c.real_name,
                //organizing_bar = c.organizing_bar,
                //corporation = c.corporation,
                //corporation_phone = c.corporation_phone,
                //business_scope = c.business_scope,
                //business_llicence = c.business_llicence,
                //face_card = c.face_card,
                //opposite_card = c.opposite_card,
                //card_date = c.card_date,
                //expiry_date = "",
            }).FirstOrDefault(i => i.id == id);
            entity.expiry_date = entity.end_time.ToShortDateString();
            return entity;
        }

        public CompanyInput GetCompanyByShopId(int shopid)
        {
            var entity = db.gw_suppliers.Include(i => i.gw_shop).FirstOrDefault(i => i.gw_shop.Count(s => s.id == shopid) > 0);
            if (null != entity)
            {
                return new CompanyInput()
                {
                    id = entity.id,
                    company_name = entity.company_name,
                    organizing_bar = entity.organizing_bar,
                    expiry_date = entity.expiry_date,
                    corporation = entity.corporation,
                    corporation_phone = entity.corporation_phone,
                    business_scope = entity.business_scope,
                    business_llicence = entity.business_llicence,
                    face_card = entity.face_card,
                    opposite_card = entity.opposite_card,
                    card_date = entity.card_date,
                    province = entity.province,
                    city = entity.city,
                    country = entity.country,
                    area = entity.area,
                    address = entity.address,
                    real_name = entity.real_name,
                    contacts_phone = entity.wordtel,
                };
            }
            else
            {
                return null;
            }
        }

        public bool IsExistCompany(string name)
        {
            return db.gw_companys.Any(i => i.name == name);
        }

        public bool SetIsComUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作商家{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_companys.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                var shopList = db.gw_shops.Where(i => i.company_id == entity.id);
                foreach (var item in shopList)
                {
                    if (null != item)
                    {
                        item.status = (byte)isUse;
                    }
                }

                entity.status = (byte)isUse;
                db.SaveChanges();
                return true;
            }
            return false;
        }
        #endregion


        #region 店铺
        public async Task<Response<int>> AddorEditShop(int managerId, ShopInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.name))
            {
                errorList.Append("店铺名称不能为空；</br>");
            }
            if (string.IsNullOrEmpty(input.mangermobile) || !Validator.IsMobile(input.mangermobile))
            {
                errorList.Append("请输入有效管理人手机号码；</br>");
            }
            if (input.account_period <= 0)
            {
                errorList.Append("账期要大于0；</br>");
            }
            //if (string.IsNullOrEmpty(input.logo) || string.IsNullOrEmpty(input.face_card) || string.IsNullOrEmpty(input.opposite_card))
            //{
            //    errorList.Append("请上传图片；</br>");
            //}
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<int>(errorList.ToString());
            }
            if (input.id > 0)
            {
                var entity = db.gw_shops.FirstOrDefault(i => i.id == input.id);
                if (entity != null)
                {
                    //entity.name = input.name;
                    entity.logo = input.logo == null ? "" : input.logo;
                    entity.grade = input.grade;
                    entity.mangername = input.mangername == null ? "" : input.mangername;
                    //entity.mangermobile = input.mangermobile;
                    entity.telephone = input.qq == null ? "" : input.telephone;
                    entity.mobile = input.qq == null ? "" : input.mobile;
                    entity.wechat = input.wechat == null ? "" : input.wechat;
                    entity.qq = input.qq == null ? "" : input.qq;
                    entity.email = input.email == null ? "" : input.email;
                    entity.face_card = input.face_card == null ? "" : input.face_card;
                    entity.opposite_card = input.opposite_card == null ? "" : input.opposite_card;
                    entity.card_date = input.card_date;
                    entity.half_card = input.half_card;
                    entity.start_date = input.start_date;
                    entity.end_date = input.end_date;
                    entity.account_period = input.account_period;
                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        LogHelper.WriteLog("管理员" + managerId + "修改：店铺" + entity.id);
                        return ReturnSuccess<int>(entity.id);
                    }
                    else
                    {
                        return ReturnError<int>("未做任何更改或保存失败，请重试！");
                    }
                }
                return ReturnError<int>("店铺信息不存在");
            }
            else
            {
                if (input.supplier_id > 0)
                {
                    var entity = new gw_shop()
                    {
                        supplier_id = input.supplier_id,
                        name = input.name,
                        logo = input.logo == null ? "" : input.logo,
                        grade = input.grade,
                        mangername = input.mangername == null ? "" : input.mangername,
                        mangermobile = input.mangermobile == null ? "" : input.mangermobile,
                        telephone = input.qq == null ? "" : input.telephone,
                        mobile = input.qq == null ? "" : input.mobile,
                        wechat = input.wechat == null ? "" : input.wechat,
                        qq = input.qq == null ? "" : input.qq,
                        email = input.email == null ? "" : input.email,
                        face_card = input.face_card == null ? "" : input.face_card,
                        opposite_card = input.opposite_card == null ? "" : input.opposite_card,
                        card_date = input.card_date,
                        half_card = input.half_card == null ? "" : input.half_card,
                        start_date = input.start_date,
                        end_date = input.end_date,
                        account_period = input.account_period,
                        add_time = DateTime.Now,
                        status = 1,
                        deleted = false
                    };
                    entity.gw_shop_property = new gw_shop_property()
                    {
                        id = entity.id,
                        goods_count = 0,
                        order_count = 0,
                        deposit = 0,
                        balances = 0
                    };
                    var model = db.gw_shops.Add(entity);
                    await db.SaveChangesAsync();
                    gw_manager manager = new gw_manager()
                    {
                        role_id = 10,
                        role_type = 2,
                        user_name = entity.mangermobile,
                        solt = RandomHelper.CreateRandomValue(6) + entity.id.ToString(),
                        logo = "",
                        real_name = entity.mangername,
                        phone = entity.mangermobile,
                        qq = entity.qq,
                        address = entity.address,
                        add_time = DateTime.Now,
                        status = 0,
                        shop_id = entity.id
                    };
                    //manager.password = SecureHelper.Get32Md5Str("123456" + manager.solt, true);
                    var pwd = "qj" + entity.id;
                    manager.password = SecureHelper.Get32Md5Str(pwd + manager.solt, true);
                    db.gw_managers.Add(manager);

                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        // 发送短信
                        string error = "";
                        if (!AliyunSmSHelper.SendSMS(manager.user_name, Core.Sms.SMSType.ShopPassword, pwd, out error))
                        {
                            LogHelper.WriteLog("店铺【" + entity.name + "】商家后台登录密码发送失败，{" + error + "}");
                        }
                        LogHelper.WriteLog("管理员" + managerId + "添加：店铺" + entity.id);
                        return ReturnSuccess<int>(model.id);
                    }
                    else
                    {
                        return ReturnError<int>("保存失败，请重试！");
                    }
                }
                else
                {
                    return ReturnError<int>("商家ID错误");
                }
            }

        }
        public IList<ShopList> GetShopsByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, string shopName, string managerName, int status, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            var list = db.gw_shops
                .Include(s => s.gw_company)
                .Where(i => i.deleted == false && i.gw_company != null)
                .Select(item => new ShopList
                {
                    id = item.id,
                    name = item.name,
                    company_name = item.gw_company.name,
                    logo = item.logo,
                    grade = item.grade,
                    mangername = item.mangername,
                    mangermobile = item.mangermobile,
                    start_date = item.start_date,
                    end_date = item.end_date,
                    status = item.status,
                    add_time = item.add_time,
                    account_period = item.account_period
                });
            if (status > -1)
            {
                list = list.Where(m => m.status == status);
            }
            if (!string.IsNullOrWhiteSpace(shopName))
            {
                list = list.Where(m => m.name.Contains(shopName));
            }
            if (!string.IsNullOrWhiteSpace(managerName))
            {
                list = list.Where(m => m.mangername.Contains(managerName));
            }
            if (!string.IsNullOrWhiteSpace(dateMin))
            {
                dtMin = DateTime.Parse(dateMin);
            }
            if (!string.IsNullOrWhiteSpace(dateMax))
            {
                dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
            }
            list = list.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }

        public ShopInput GetShopById(int id)
        {
            var entity = db.gw_shops.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                return new ShopInput()
                {
                    id = entity.id,
                    supplier_id = entity.supplier_id,
                    name = entity.name,
                    logo = entity.logo,
                    grade = entity.grade,
                    econtent = entity.econtent,
                    face_card = entity.face_card,
                    opposite_card = entity.opposite_card,
                    card_date = entity.card_date,
                    province = entity.province,
                    city = entity.city,
                    country = entity.country,
                    area = entity.area,
                    address = entity.address,
                    mangername = entity.mangername,
                    mangermobile = entity.mangermobile,
                    telephone = entity.telephone,
                    mobile = entity.mobile,
                    wechat = entity.wechat,
                    qq = entity.qq,
                    email = entity.email,
                    half_card = entity.half_card,
                    start_date = entity.start_date,
                    end_date = entity.end_date,
                    account_period = entity.account_period
                };
            }
            else
            {
                return null;
            }
        }

        public bool IsExistShop(string name)
        {
            return db.gw_shops.Any(i => i.name == name);
        }

        public bool SetIsShopUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作店铺{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_shops.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.status = (byte)isUse;
                db.SaveChanges();
                return true;
            }
            return false;
        }

        public List<ShopCategoryDto> GetShopCategoryList(int id)
        {
            var list = from sc in db.gw_shop_category_mappings
                       join gc in
                       (from c in db.gw_goods_categories
                        join fc in db.gw_goods_categories.DefaultIfEmpty() on c.parent_id equals fc.id
                        select new
                        {
                            id = c.id,
                            name = c.name,
                            parentId = fc.id,
                            parentName = fc.name
                        }).DefaultIfEmpty() on sc.category_id equals gc.id
                       where sc.shop_id == id
                       orderby sc.type_id
                       select new ShopCategoryDto
                       {
                           Id = sc.id,
                           ShopId = (int)sc.shop_id,
                           TypeId = sc.type_id == null ? 0 : (int)sc.type_id,
                           CategoryTwoId = sc.category_id == null ? 0 : (int)sc.category_id,
                           CategoryOneId = gc.parentId,
                           CategoryOneName = gc.parentName,
                           CategoryTwoName = gc.name
                       };
            return list.ToList();
        }

        public ShopCategoryDto GetShopCategory(int shopId, int categoryId, int type)
        {
            var model = from sc in db.gw_shop_category_mappings
                        join gc in
                        (from c in db.gw_goods_categories
                         join fc in db.gw_goods_categories.DefaultIfEmpty() on c.parent_id equals fc.id
                         select new
                         {
                             id = c.id,
                             name = c.name,
                             parentId = fc.id,
                             parentName = fc.name
                         }).DefaultIfEmpty() on sc.category_id equals gc.id
                        where sc.shop_id == shopId && sc.category_id == categoryId && sc.type_id == type
                        select new ShopCategoryDto
                        {
                            Id = sc.id,
                            ShopId = (int)sc.shop_id,
                            TypeId = sc.type_id == null ? 0 : (int)sc.type_id,
                            CategoryTwoId = sc.category_id == null ? 0 : (int)sc.category_id,
                            CategoryOneId = gc.parentId,
                            CategoryOneName = gc.parentName,
                            CategoryTwoName = gc.name
                        };
            return model.ToList().FirstOrDefault();
        }

        public async Task<Response<int>> SetShopCategory(int managerId, int id, List<ShopCategoryInput> addList, List<ShopCategoryInput> delList)
        {
            List<ShopCategoryInput> addListDel = new List<ShopCategoryInput>();
            List<ShopCategoryInput> delListDel = new List<ShopCategoryInput>();
            List<int> delArr = new List<int>();
            if (addList != null && delList != null)
            {
                foreach (var add in addList)
                {
                    foreach (var del in delList)
                    {
                        if (add.TypeId == del.TypeId && add.CategoryOneId == del.CategoryOneId && add.CategoryTwoId == del.CategoryTwoId)
                        {
                            addListDel.Add(add);
                            delListDel.Add(del);
                        }
                    }
                }
            }
            foreach (var item in addListDel)
            {
                addList.Remove(item);
            }
            foreach (var item in delListDel)
            {
                delList.Remove(item);
            }
            List<gw_shop_category_mapping> addRange = new List<gw_shop_category_mapping>();
            if (addList != null)
            {
                foreach (var add in addList)
                {
                    addRange.Add(new gw_shop_category_mapping
                    {
                        type_id = add.TypeId,
                        shop_id = id,
                        category_id = add.CategoryTwoId == 0 ? add.CategoryOneId : add.CategoryTwoId
                    });
                }
            }
            if (delList != null)
            {
                foreach (var del in delList)
                {
                    delArr.Add(del.Id);
                }
            }
            //TODO:添加时判定数据库是否已经存在
            if (addRange.Count == 0 && delArr.Count == 0)
            {
                return ReturnError<int>("未做更改！");
            }
            var delRange = db.gw_shop_category_mappings.Where(i => delArr.Contains(i.id));
            db.gw_shop_category_mappings.RemoveRange(delRange);
            db.gw_shop_category_mappings.AddRange(addRange);
            var result = await db.SaveChangesAsync();
            if (result > 0)
            {
                return ReturnSuccess<int>(result);
            }
            else
            {
                return ReturnError<int>("保存失败，请重试!");
            }
        }

        public int SendGroupMsg()
        {
            int count = 0;
            var shopList = db.gw_shops.Where(i => i.mangermobile != "18037867134").ToList();
            foreach (var item in shopList)
            {
                string error = "";
                string pwd = "qj" + item.id;

                if (!AliyunSmSHelper.SendSMS(item.mangermobile, Core.Sms.SMSType.ShopPassword, pwd, out error))
                {
                    LogHelper.WriteLog("店铺【" + item.name + "】商家后台登录密码发送失败，{" + error + "}");
                }
                else
                {
                    count++;
                }
            }
            return count;
        }
        #endregion
    }
}
